const db = wx.cloud.database();
const shanbeiHost = "https://www.shanbay.com/bdc/vocabulary/";

var questionIdx = 1;
var inter = null;
//抓取单词
const getWords = () => {
  //inter = setInterval(intervalQuery, 1000);
  intervalQuery();
}

//定时去请求该函数
const intervalQuery = () => {
  let url = shanbeiHost + questionIdx+"/";
  console.info("questionIdx==" + questionIdx);
  questionIdx++;
  if (questionIdx > 99999 && null != inter)
  {
    clearInterval(inter);
    return;
  }
  wx.request({
    url: url,
    header: {
      'content-type': 'application/json' // 默认值
    },
    success(res) {
      let resData = res.data;
      //console.info(resData);
      var htmlArr = resData.match(/<div class=\"container main-body([\s\S]*?)container -->/g);
      let htmlBase = htmlArr[0];

      //console.info(htmlBase);
      parseWordHtml(htmlBase);
    }
  })
}

//解析html
const parseWordHtml = baseHtml => {
  
  //<h1 class="content pull-left" style="">puddle <small>
  let wordArr = baseHtml.match(/<h1 class=\"content pull-left\"([\s\S]*?)<small>/g);
  if (null == wordArr || wordArr.length==0)
  {
    //没有找到单词
    return;
  }

  //单词
  let word = wordArr[0];

  //音频
  let audio_uk = baseHtml.match(/<span class=\"audio uk\"([\s\S]*?)>/g);
  let audio_us = baseHtml.match(/<span class=\"audio us\"([\s\S]*?)>/g);

  if (null != audio_uk)
  {
    audio_uk = audio_uk[0];
  }
  if (null != audio_us) {
    audio_us = audio_us[0];
  }

  //中文解释
  let explain_cn = baseHtml.match(/<span class="text">([\s\S]*?)<\/span>/g);
  if (null == explain_cn) { explain_cn =[]};

  //英文解释标签  <span class="part-of-speech label">verb</span>
  let explain_en_lable = baseHtml.match(/<span class=\"part-of-speech label\">([\s\S]*?)<\/span>/g);
  if (null == explain_en_lable) { explain_en_lable = [] };

  //英文解释<span class="content">a small area of collected liquid or muddy water</span>
  let explain_en = baseHtml.match(/<ol class=\"span7\">([\s\S]*?)<\/ol>/g);
  if (null == explain_en) { explain_en = [] };


  let example_en = baseHtml.match(/<div class=\"annotation enex\">([\s\S]*?)<\/div>/g);
  if (null == example_en) { example_en = [] };

  let example_cn = baseHtml.match(/<div class=\"cnex\">([\s\S]*?)<\/div>/g);
  if (null == example_cn) { example_cn = [] };

  //删除html并trim得到单词
  word = removeHtml(word).trim();
  if (null != audio_uk)
  {
    audio_uk = audio_uk.match(/https:\/\/media([\s\S]*?).mp3/)[0];
  }

  if (null != audio_us)
  {
    audio_us = audio_us.match(/https:\/\/media([\s\S]*?).mp3/)[0];
  }

  let symbol = baseHtml.match(/<small>([\s\S]*?)<\/small>/g);
  if (null != symbol)
  {
    symbol = symbol[0];
    symbol = removeHtml(symbol);
  }

  //剔除html，得到中文解释
  explain_cn = explain_cn.map(function (item) {
    item = item.replace(/<\/?.+?>/g, "");
    return item;
  });

  //剔除html，
  explain_en_lable = explain_en_lable.map(function (item) {
    item = item.replace(/<\/?.+?>/g, "");
    return item;
  });


  // <ol class="span7">
  //   <li class="definition">
  //     <span class="content">to roll around in muddy water, make water muddy or create a small collection of muddy water</span>
  //   </li>
  //   <li class="definition">
  //     <span class="content">completely and absolutely (`good' is sometimes used informally for `thoroughly')</span>
  //   </li>
  // </ol>

  //处理英文解释，一个类型可能会对应多个解释
  explain_en = explain_en.map(function (item) {
    
    var subArr = item.match(/<span class=\"content\">([\s\S]*?)<\/span>/g);
    if(null==subArr)
    {
      subArr = [];
    }
    subArr = subArr.map(function (subItem) {
      subItem = subItem.replace(/<\/?.+?>/g, "");
      subItem = htmlDecode(subItem);
      return subItem;
    });
    return subArr;
  });

  //剔除html，
  example_en = example_en.map(function (item) {
    item = item.replace(/<\/?.+?>/g, "");
    item = htmlDecode(item);
    item = item.trim();
    return item;
  });

  //剔除html，
  example_cn = example_cn.map(function (item) {
    item = item.replace(/<\/?.+?>/g, "");
    return item;
  });

  // console.info(word);
  // console.info(audio_uk);
  // console.info(audio_us);
  // console.info(explain_cn);
  // console.info(explain_en_lable);
  // console.info(explain_en);
  //console.info(example_en);
  //console.info(htmlDecode("He&#39;s almost"));
  // console.info(example_cn);
  // console.info(isWord(word));

  if (isWord(word))
  {
    db.collection('words').where({
      word: word
    }).get().then(res => {
          
      if (res.data.length > 0) {
        var wordDB = res.data[0];
        db.collection('words').doc(wordDB._id).update({
          data: {
            audio_uk: audio_uk,
            audio_us: audio_us,
            explain_cn: explain_cn,
            explain_en: getExplainEn(explain_en_lable, explain_en),
            example_sb: getExampleShanBei(example_en, example_cn)
          },
          success(res) {
            console.info("单词" + word + "更新成功");
          },
          fail(res) {
            console.error("单词" + word + "更新失败");
          }
        })

      } else {
        var wordDB = {
          word: word,
          symbol: symbol,
          audio_uk: audio_uk,
          audio_us: audio_us,
          explain_cn: explain_cn,
          explain_en: getExplainEn(explain_en_lable, explain_en),
          example_sb: getExampleShanBei(example_en, example_cn)
        };
        db.collection('words').add({
          data: wordDB
        })
          .then(res => {
            console.info("单词" + word + "保存成功");
          })
          .catch(e => {
            console.error("单词" + word + "保存失败");
          })
      }
      
    })
  }else
  {
    //如果是词组
    db.collection('word_phrase').where({
      phrase: word
    }).get().then(res => {
      

      if (res.data.length > 0) {
        var wordDB = res.data[0];
        db.collection('word_phrase').doc(wordDB._id).update({
          data: {
            symbol: symbol,
            audio_uk: audio_uk,
            audio_us: audio_us,
            explain_cn: explain_cn,
            explain_en: getExplainEn(explain_en_lable, explain_en),
            example_sb: getExampleShanBei(example_en, example_cn)
          },
          success(res) {
            console.info("词组" + word + "更新成功");
          },
          fail(res) {
            console.error("词组" + word + "更新失败");
          }
        })

      } else {
        var wordDB = {
          phrase: word,
          symbol: symbol,
          audio_uk: audio_uk,
          audio_us: audio_us,
          explain_cn: explain_cn,
          explain_en: getExplainEn(explain_en_lable, explain_en),
          example_sb: getExampleShanBei(example_en, example_cn)
        };
        db.collection('word_phrase').add({
          data: wordDB
        })
          .then(res => {
            console.info("词组" + word + "保存成功");
          })
          .catch(e => {
            console.error("词组" + word + "保存失败");
          })
      }


    })
  }
}


const getExampleShanBei = (example_en, example_cn) => {
  let exampleArr = [];
  for (var i = 0; i < example_en.length;i++)
  {
    var example = {};
    example.en = example_en[i];
    example.cn = example_cn[i];
    exampleArr.push(example);
  }
  
  return exampleArr;
}


const getExplainEn = (explain_en_lable, explain_en) => {
  let explainArr = [];
  for (var i = 0; i < explain_en_lable.length; i++) {  
    var explain = {};
    explain.lable = explain_en_lable[i];
    explain.value = explain_en[i];
    explainArr.push(explain);
  }
  return explainArr;
}


const isWord = word => {
  //如果有空格说明是词组
  if (word.search(" ") != -1)
  {
    return false;
  }
  return true;
}

const removeHtml = html => {
  html = html.replace(/<\/?.+?>/g, "");
  return html;
}

//html的 ' 字符转换
const htmlDecode = (str) => {
  return str.replace(/&#(x)?([^&]{1,5});/g, function ($, $1, $2) {
    return String.fromCharCode(parseInt($2, $1 ? 16 : 10));
  });
};


module.exports = {
  getWords: getWords
}